﻿using System.Collections.Generic;

namespace Sidvall.AuthorizationManager.Data
{
	public class ClaimItemCollectionDictionary : Dictionary<string, ClaimItemCollection>
	{
		#region Public Members

		#region GetClaimItem

		public ClaimItem GetClaimItem(string claimType, string value)
		{
			ClaimItemCollection items;

			if (string.IsNullOrWhiteSpace(claimType))
				return null;
			if (TryGetValue(claimType.Trim(), out items))
				return AuthorizationScopeItemManager.GetClaimItem(items, value);
			return null;
		}

		#endregion
		#region GetDescription

		public string GetDescription()
		{
			string value = string.Empty;
			foreach (var item in this)
			{
				if (!string.IsNullOrWhiteSpace(value))
					value += "; ";
				value += item.Key + ": " + item.Value.GetDescription();
			}
			return value;
		}

		#endregion
		#region Load

		public void Load(IEnumerable<IClaimItem> items)
		{
			ClaimItemCollection claimItems;
			ClaimItem claimItem;
			string claimType;

			if (items == null)
				return;
			foreach (var item in items)
			{
				if (!item.IsEnabled)
					continue;
				if (string.IsNullOrWhiteSpace(item.ClaimType))
					continue;
				claimType = item.ClaimType.Trim();
				if (!TryGetValue(claimType, out claimItems))
				{
					claimItems = new ClaimItemCollection();
					Add(claimType, claimItems);
				}
				claimItem = new ClaimItem(item.Value, item.ComparisonOperator);
				claimItems.Add(claimItem);
			}
		}

		#endregion

		#endregion
		#region Constructors

		public ClaimItemCollectionDictionary()
			: base()
		{

		}
		public ClaimItemCollectionDictionary(IEqualityComparer<string> comparer)
			: base(comparer)
		{
		}

		#endregion
	}
}
